package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.vo.IotMsgService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author Winnie
 * @date 2025-10-19
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper,DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData)?1:0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData)?1:0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id)?1:0;
    }
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;
    @Override
    public void batchInsertFromContentStr(String contentStr) {
        if (contentStr == null){
            return;
        }
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);

        //通过设备id获取设备
        String iotId = jsonObject.getByPath("notify_data.header.device_id", String.class);
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(queryWrapper);
        // 如果设备不存在就不需要继续了
        if(device==null){
            return;
        }


        JSONObject properties  = (JSONObject)jsonObject.getByPath("notify_data.body.services[0].properties");

        Set<String> keys = properties.keySet();

        String eventTimeStr = jsonObject.get("event_time", String.class);
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTimeStr,"yyyyMMdd'T'HHmmss'Z'");

        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(parse);

        // 准备接受要保存的设备数据
        List<DeviceData> list = new ArrayList<>();
        for (String key : keys) {
            Object value = properties.get(key);

            DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
            deviceData.setId(null); // 不能用device中的id
            deviceData.setAccessLocation(device.getBindingLocation());

            deviceData.setFunctionId(key);
            deviceData.setDataValue(value+"");
            deviceData.setAlarmTime(eventTime);

            // 收集起来方便批量保存
            list.add(deviceData);

        }

        try {
            saveBatch(list);
            redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).put(iotId,JSONUtil.toJsonStr(list));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    @Override
    public void cleanOlData(Integer minute) {
        //查询十分钟前的最后一个id值
        Long id =  deviceMapper.getLastId(minute);
        //把小于等于这个id的值全部移入历史表
        deviceMapper.insertHistory(id);
        //删除旧表中的数据
        deviceMapper.deleteOldId(id);
    }


}
